#include "CCSkeleton.h"
#include "CCSpineGlobal.h"



CCSkeleton::CCSkeleton() {
    _ary=new Array();
}

CCSkeleton::~CCSkeleton() {
	for(auto it: m_boneMap) {
		it.second->release();
	}
    m_boneMap.clear();
    
    for(auto it: m_slotDisplayList) {
		it->release();
	}
    m_slotMap.clear();
    m_slotDisplayList.clear();
    
    for(auto it: m_skinMap) {
		it.second->release();
	}
    m_skinMap.clear();
    
    for(auto it: m_animMap) {
		it.second->release();
	}
    m_animMap.clear();
    
    delete _ary;
}

CCSkeleton* CCSkeleton::create() {
	CCSkeleton* s = new CCSkeleton();
	return (CCSkeleton*)s->autorelease();
}

void CCSkeleton::addBone(CCBone* bone) {
	BoneMap::iterator iter = m_boneMap.find(bone->getName());
	if(iter == m_boneMap.end()) {
		m_boneMap[bone->getName()] = bone;
		bone->retain();
	}
}

void CCSkeleton::addSlot(CCSlot* slot) {
	SlotMap::iterator iter = m_slotMap.find(slot->getName());
	if(iter == m_slotMap.end()) {
		m_slotMap[slot->getName()] = slot;
		m_slotDisplayList.push_back(slot);
		slot->retain();
	}
}

void CCSkeleton::addSkin(CCSkin* skin) {
    SkinMap::iterator iter = m_skinMap.find(skin->getName());
	if(iter == m_skinMap.end()) {
		m_skinMap[skin->getName()] = skin;
		skin->retain();
	}
}

void CCSkeleton::addAnim(CCSkeletalAnimation *anim) {
    AnimationMap::iterator iter=m_animMap.find(anim->getName());
    if (iter==m_animMap.end()) {
        m_animMap[anim->getName()] = anim;
        anim->retain();
        _ary->addObject(anim);
    }
}

CCBone* CCSkeleton::getRootBone() {
	if(m_boneMap.size())
	{
		CCBone* bone=m_boneMap.begin()->second;
		while(bone->getParent()!=NULL) {
			bone=bone->getParent();
		}
		return bone;
	}
	return NULL;
}

CCBone* CCSkeleton::getBone(const char* name) {
	if(!name) {
	   return NULL;
	}
	BoneMap::iterator iter = m_boneMap.find(name);
	if(iter != m_boneMap.end()) {
		return iter->second;
	} else {
		return NULL;
	}
}

CCSlot* CCSkeleton::getSlot(const char* name) {
	if(!name) {
		return NULL;
	}
	SlotMap::iterator iter = m_slotMap.find(name);
	if(iter != m_slotMap.end()) {
		return iter->second;
	} else {
		return NULL;
	}
}

CCSkin* CCSkeleton::getSkin(const char* name) {
    if(!name) {
		return NULL;
    }
	SkinMap::iterator iter = m_skinMap.find(name);
	if(iter != m_skinMap.end()) {
		return iter->second;
	} else {
		return NULL;
	}
}

CCSkeletalAnimation* CCSkeleton::getAnim(const char *name) {
    if (!name) {
        return NULL;
    }
    AnimationMap::iterator iter=m_animMap.find(name);
    if (iter!=m_animMap.end()) {
        return iter->second;
    }
    else {
        return NULL;
    }
}

CCSkeletalAnimation* CCSkeleton::getAnimRandom() {
    return (CCSkeletalAnimation*)_ary->randomObject();
}


